﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Composition;
using SoundEdge.Media.Wave;
using SoundEdge.Media.Settings;
using SoundEdge.Media.CoreAudioApi;

namespace SoundEdge.Media.Wave.Plugins
{
    [Export(typeof(IOutputDevicePlugin))]
    public class WasapiOutPlugin : IOutputDevicePlugin
    {
        private WasapiOutSettings _settings;
        public IOutputSettings Settings
        {
            get { return _settings; }
        }

        public WasapiOutPlugin()
        {
            _settings = WasapiOutSettings.LoadSettings<WasapiOutSettings>("settings.xml");
            if (_settings == null)
            {
                _settings = new WasapiOutSettings();
            }
        }

        public IWavePlayer CreateDevice()
        {
            var enumerator = new MMDeviceEnumerator();
            var endPoints = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

            MMDevice device = endPoints.FirstOrDefault(item => item.ID == _settings.MMDeviceId);

            if (device == null)
            {
                return null;
            }

            var wasapi = new WasapiOut(
                device,
                _settings.ShareMode,
                _settings.EventCallback,
                _settings.Latency);
            return wasapi;
        }

        public virtual UserControl CreateSettingsPanel()
        {
            throw new NotSupportedException();
        }

        public string Name
        {
            get { return "WasapiOut"; }
        }

        public bool IsAvailable
        {
            // supported on Vista and above
            get { return Environment.OSVersion.Version.Major >= 6; }
        }

        public int Priority
        {
            get { return 3; }
        }
    }
}
